# app/api/routes/students.py
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

from app.core.database import get_db
from app.schemas import schemas
from app.crud import crud
from app.api.routes.auth import get_current_user

router = APIRouter()


@router.get("/", response_model=List[schemas.Student])
def read_students(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    return crud.get_students(db, skip=skip, limit=limit)


@router.post("/", response_model=schemas.Student)
def create_student(
    student: schemas.StudentCreate,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    return crud.create_student(db=db, student=student)


@router.delete("/{student_id}")
def delete_student(
    student_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    print(f"deleting student: {student_id}")
    if student_id is None:
        raise HTTPException(status_code=400, detail="请提供学生ID")
    result = crud.delete_student(db, student_id)
    if result is None:
        raise HTTPException(status_code=400, detail="删除失败")
    return {"status": "success", "message": "删除成功"}


@router.post("/recharge")
def recharge_student(
    recharge: schemas.RechargeCreate,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    result = crud.recharge_student(db=db, recharge=recharge, user_id=current_user.id_)
    if not result:
        raise HTTPException(status_code=400, detail="充值失败")
    return {"message": "充值成功"}


@router.get("/{student_id}/recharges")
def read_student(
    student_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    if student_id is None:
        raise HTTPException(status_code=400, detail="请提供学生ID")
    return crud.get_recharges(db, student_id)


@router.get("/{student_id}")
def get_student_by_id(
    student_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    result = crud.get_student(db, student_id)
    if result is None:
        raise HTTPException(status_code=400, detail="学生不存在")
    return result